﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace LingDingSoft.Service
{
    public class ServiceBase
    {
        public string SendRequest(string id, string action, Dictionary<string, object> Params)
        {
            if (Params == null)
            {
                Params = new Dictionary<string, object>();
            }
            Parameter.RequestParameter model = new Parameter.RequestParameter();
            model.action = action;
            model.id = id;
            model.metas = new Parameter.RequestMetas() { app_key = AppConfig.GetAppKey(), timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc)).TotalSeconds };
            model.token = AppConfig.GetToken()?.access_token;
            model.Params = Params;
            model.signature = new SignatureCreater(model.Params, model.metas, model.action, model.token, AppConfig.GetSecret()).GetResult();


            var helper = new Http.HttpRequestHelper();
            return helper.SendRequest(AppConfig.GetAPIUrl(), new Http.JsonBodyWriter(Newtonsoft.Json.JsonConvert.SerializeObject(model)));
        }
        /// <summary>
        /// 返回结果，出错则返回null;
        /// </summary>
        /// <param name="action"></param>
        /// <param name="Params"></param>
        /// <returns></returns>
        public T SendRequestEx<T>( string action, Dictionary<string, object> Params)
        {
            string id = System.Guid.NewGuid().ToString();
            var vRts = SendRequest(id, action, Params);
            var model = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.ResponseModel<T>>(vRts);
            if (model != null)
            {
                if (id!=model.id)
                {
                    //非法交互 自行处理
                    return default(T);
                }
                //没有错误时，返回得到的请求对象
                if (model.error == null)
                {
                    return model.result;
                }
                else
                {
                    //处理异常
                }
            }
            return default(T);

        }
    }
}
